import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap-datepicker/dist/css/bootstrap-datepicker3.css';
require('../css/purchase/pubpurchase.less');
require('../css/purchase/index.less');
require('../css/purchase/common.less');


var $ = require('jquery');
import 'bootstrap/dist/js/bootstrap.min.js';
import 'bootstrap-datepicker/dist/js/bootstrap-datepicker.js';
import 'jquery-validation/dist/jquery.validate.js';
import 'jquery-validation/dist/localization/messages_zh.js';

let headerTemplate = require('../view/templateWidget/header.hbs');
let footerTemplate = require('../view/templateWidget/footer.hbs');
let addRowTemplate = require('../view/templateWidget/addRow.hbs');

$('header').html(headerTemplate);
$('footer').html(footerTemplate);
require('../helper/header.js'); //搜索栏切换placeholder及搜索为空校验
require('../helper/helper.js'); // 日期插件切换为中文显示
var rowCount;
// 日期插件
$('#deadline').datepicker({
    autoclose: true, //自动关闭  
    format: 'yyyy-mm-dd', //日期格式 
    language: 'cn', //语言
    todayHighlight: true, //今天高亮
    startDate: new Date(),
});
// 获取询价物品数量 
rowCount = $('#addTr').find('tr').length;
// 点击添加按钮增加一行最多添加10行
$("#adds").on('click', function () {
    if (rowCount < 10) {
        $("#addTr").append(addRowTemplate);
        rowCount++;
        rowNum();
        reIndex();
    } else {
        return false;
    }
})
// 点击后面的删除按钮删除当前行
$("#addTr").delegate('.removeBtn', 'click', function () {
    $(this).closest('tr').remove();
    rowCount--;
    rowNum();
    reIndex();

});
// 重置索引及动态添加表单校验
function reIndex() {
    $('.tabTr').each(function (i) {
        //获取当前tr的id
        var id = $(this).attr('id');
        $(this).attr('id', id.replace(/\d/, i));
        $(this).find('.bor_look').each(function () {
            var obj = $(this);
            var id = $(obj).attr('id');
            var name = $(obj).attr('name');
            $(obj).attr('id', id.replace(/\d/, i));
            $(obj).attr('name', name.replace(/\d/, i));
        });
    });
    $("input[name^='goods_name']").each(function () {
        $(this).rules("add", {
            required: true,
            messages: {
                required: "请输入物品名称"
            }
        });
    })
    $("input[name^='cat_id_box']").each(function () {
        $(this).rules("add", {
            required: true,
            messages: {
                required: "请选择所属分类"
            }
        });
    })
    $("input[name^='purchase_number']").each(function () {
        $(this).rules("add", {
            required: true,
            number: true,
            range: [0, 999999999],
            messages: {
                required: "请输入正确的采购量"
            }
        });
    })
    $("input[name^='unit']").each(function () {
        $(this).rules("add", {
            required: true,
            messages: {
                required: "请填写采购单位"
            }
        });
    })
}
// 判断表格行数是否大于1
function rowNum() {
    if (rowCount > 1) {
        $('.removeBtn').css('display', 'inline-block');
    } else if (rowCount === 1) {
        $('.removeBtn').css('display', 'none');
    }
}
// 判断报价含税是否被选中
$("#haveTaxFlag").click(function () {
    var checked = $("#haveTaxFlag").prop("checked");
    if (checked) {
        $("#invoice_tax").show();
    } else {
        $("#invoice_type").val("");
        $("#tax_rate").val("");
        $("#invoice_tax").hide();
    };
});
// 客户类型是企业采购时显示公司名称
$('input[name="buyer_type"]').click(function () {
    if ($(this).val() === "1") {
        $(".company_name").hide();
    } else {
        $(".company_name").show();
    }
});
//用于发布采购表单验证
var vali;
// 验证手机号码
$.validator.addMethod("isMobile", function (value, element) {
    var length = value.length;
    var mobile = /^(13[0-9]{9})|(18[0-9]{9})|(14[0-9]{9})|(17[0-9]{9})|(15[0-9]{9})$/;
    return this.optional(element) || (length == 11 && mobile.test(value));
});
vali = $("#pubpurchForm").validate({
    // debug:true, //调试模式，即使验证成功也不会跳转到目标页面
    rules: {
        title: "required",
        purchase_type: "required",
        deadline: "required",
        delivery: "required",
        invoice_type: 'required',
        tax_rate: 'required',
        buyer_type: 'required',
        contact_info: 'required',
        contact_name: 'required',
        contact_mobile: {
            required: true,
            isMobile: true
        },
        info_open: 'required',
        'goods_name[0]': 'required',
        'cat_id_box[0]': 'required',
        'purchase_number[0]': {
            required: true,
            number: true,
            range: [0, 999999999]
        },
        'unit[0]': 'required',
        // 注册资本非必录项
        'registered_capital': {
            number: true,
            range: [0, 999999999]
        }
    },
    messages: {
        title: "请输入询价单标题",
        purchase_type: "请选择采购类型",
        deadline: "请选择报价截止时间",
        delivery: "请选择交货地",
        invoice_type: '请选择发票类别',
        tax_rate: '请填写税率',
        buyer_type: '请选择客户类型',
        contact_info: '请输入公司名称',
        contact_name: '请输入联系人',
        contact_mobile: {
            required: "请输入手机号",
            isMobile: "请正确填写您的手机号码"
        },
        info_open: '请选择信息公开方式',
        'goods_name[0]': '请输入物品名称',
        'cat_id_box[0]': '请选择所属分类',
        'purchase_number[0]': '请输入正确的采购量',
        'unit[0]': '请填写采购单位',
    },
    errorPlacement: function (error, element) {
        error.appendTo(element.parent());
    },
});
// 选择日期之后删除错误提示
$('#deadline').on('change', function () {
    $(this).focus();
    $(this).blur();
})

// 省市二级联动
$.ajax({
    type: "get",
    url: "http://purchasing.mhw001.com/getDistrictList",
    dataType: "json",
    success: function (result) {
        console.log(result);
        var option1 = '';
        for (var i = 0; i < result.data.length; i++) {
            option1 += '<option value="' + result.data[i].district_id + '">' + result.data[i].district_name + '</option>';
        }
        $('#province,#area_pro').append(option1);
    }
});
$('#province').on("change", function () {
    var proid = $('#province').val();
    $.ajax({
        type: "get",
        url: "http://purchasing.mhw001.com/getDistrictList",
        dataType: "json",
        data: {
            'district_id': proid
        },
        success: function (res) {
            var option2 = '';
            for (var i = 0; i < res.data.length; i++) {
                option2 += '<option value="' + res.data[i].district_id + '">' + res.data[i].district_name + '</option>';
            }
            $('#city').empty().append(option2);
        }
    })
})
$('#area_pro').on("change", function () {
    var proid = $('#area_pro').val();
    $.ajax({
        type: "get",
        url: "http://purchasing.mhw001.com/getDistrictList",
        dataType: "json",
        data: {
            'district_id': proid
        },
        success: function (res) {
            var option2 = '';
            for (var i = 0; i < res.data.length; i++) {
                option2 += '<option value="' + res.data[i].district_id + '">' + res.data[i].district_name + '</option>';
            }
            $('#area_city').empty().append(option2);
        }
    })
})
// 上传图片
var imageForm = new FormData();
$("#addTr").delegate('.uploadImg', 'change', function () {
    var obj = $(this);
    imageForm.append("upfile", $(obj).get(0).files[0]);
    // console.log($(obj).get(0).files[0]);
    $.ajax({
        url: "http://base.mhw.com/index.php?ctl=Upload&action=uploadImage",
        type: 'POST',
        cache: false,
        data: imageForm,
        processData: false,
        contentType: false,
        dataType: "json",
        success: function (data) {
            console.log(data);
            var picTitle = data.title;
            var picUrl = data.url;
            // console.log(picTitle);
            $(obj).parent().hide();
            $(obj).parent().parent().find(".afterUpload").show();
            $(obj).parent().parent().find(".uploadTitle").text(picTitle);
            $(obj).next().val(picUrl);
        }
    });
})

// 上传文件
$("#addFile").on("change", function () {
    var obj = $(this);
    var fileForm = new FormData();
    fileForm.append("upfile", $(obj).get(0).files[0]);
    // console.log(fileForm);
    $.ajax({
        url: "http://base.mhw.com/index.php?ctl=Upload&action=uploadFiles",
        type: 'POST',
        cache: false,
        data: fileForm,
        processData: false,
        contentType: false,
        dataType: "json",
        success: function (data) {
            console.log(data);
            var fileTitle = data.original;
            var fileUrl = data.url;
            // console.log(fileUrl);
            $('.uploadAttach').hide();
            $('.attachBox').show();
            $(".attachTitle").text(fileTitle);
            $('#accessory').val(fileUrl);
        }
    });
})

$("#addTr").delegate('.delBtn', 'click', function () {
    $(this).prev().text('');
    $(this).parent().parent().find(".uploadUrl").val('');
    $(this).parent().parent().find(".uploadImg").val('');
    $(this).parent().parent().find(".beforeUpload").show();
    $(this).parent().hide();
});
$(".reChoose").on("click", function () {
    $(".attachTitle").text('');
    $('#accessory').val('');
    $("#addFile").val('');
    $(".uploadAttach").show();
    $(".attachBox").hide();
})
// 发布采购提交表单
$('.imd_pub_btn').on('click', function () {
    if (vali.form()) {
        var formCont = new FormData($("#pubpurchForm")[0]);
        $.ajax({
            type: "POST",
            url: 'http://purchasing.mhw001.com/addPurchasingInfo',
            data: formCont,
            cache: false,
            processData: false,
            contentType: false,
            // async: false,  
            success: function (data) {
                // 判断返回状态
                if (data.code == "1") {
                    // console.log(data);
                    alert("发布成功!");
                } else {
                    return data.message
                }
            },
            error: function (request) {
                alert("系统错误!");
            }
        });
    } else {
        return false;
    }
})
var chooseId = ''; //返回后台id
var textCont = ''; //所有选择内容
var text1 = ''; //一级分类的选择内容
var text2 = ''; //二级分类的选择内容
var text3 = ''; //三级分类的选择内容
var chooseList = ''; //点击选择的所属分类框点击弹出三级联动
$("#addTr").delegate('.choose_trade_type', 'focus', function () {
    chooseId = '';
    textCont = '';
    chooseList = $(this);
    $("#showdiv").show();
    $("#pop").show();
    $.ajax({
        type: "get",
        url: "http://purchasing.mhw001.com/getCatName",
        dataType: "json",
        success: function (result) {
            // console.log(result.data);
            var li1 = '';
            for (var i = 0; i < result.data.length; i++) {
                li1 += '<li class="firstList" id="' + result.data[i].cat_id + '">' +
                    '<a href="javascript:void(0)">' + result.data[i].cat_name +
                    '<i class="icon_gt">' + '</i>' +
                    '</a>' +
                    '</li>'
            }
            $('#firstCata').empty().append(li1);
        }
    });
});
$("#firstCata").delegate('.firstList', 'click', function () {
    $('.firstList').removeClass('hove');
    $(this).addClass('hove');
    var catId1 = $(this).attr("id");
    text1 = $(this).text();
    // console.log(catId);
    $.ajax({
        type: "get",
        url: "http://purchasing.mhw001.com/getCatName",
        dataType: "json",
        data: {
            cat_parent_id: catId1
        },
        success: function (result) {
            // console.log(result.data);
            var li2 = '';
            if (result.data.length == 0) {
                textCont = text1;
                chooseId = catId1;
                return false;
            } else {
                for (var i = 0; i < result.data.length; i++) {
                    li2 += '<li class="secondList" id="' + result.data[i].cat_id + '">' +
                        '<a href="javascript:void(0)">' + result.data[i].cat_name +
                        '<i class="icon_gt">' + '</i>' +
                        '</a>' +
                        '</li>'
                }
            }
            $('#secondCata').empty().append(li2);
        }
    });
});
$("#secondCata").delegate('.secondList', 'click', function () {
    $('.secondList').removeClass('hove');
    $(this).addClass('hove');
    var catId2 = $(this).attr("id");
    text2 = $(this).text();
    // console.log(catId);
    $.ajax({
        type: "get",
        url: "http://purchasing.mhw001.com/getCatName",
        dataType: "json",
        data: {
            cat_parent_id: catId2
        },
        success: function (result) {
            // console.log(result.data);
            var li3 = '';
            if (result.data.length == 0) {
                textCont = text1 + '/' + text2;
                chooseId = catId2;
                return false;
            } else {
                for (var i = 0; i < result.data.length; i++) {
                    li3 += '<li class="thirdList" id="' + result.data[i].cat_id + '">' +
                        '<a href="javascript:void(0)">' + result.data[i].cat_name +
                        '</a>' +
                        '</li>'
                }
            }
            $('#thirdCata').empty().append(li3);
        }
    });
});
$("#thirdCata").delegate('.thirdList', 'click', function () {
    $('.thirdList').removeClass('hove');
    $(this).addClass('hove');
    var catId3 = $(this).attr("id");
    text3 = $(this).text();
    textCont = text1 + '/' + text2 + '/' + text3;
    chooseId = catId3;
});
$('#claseBtn').on('click', function () {
    $(chooseList).val(textCont);
    $(chooseList).focus();
    $(chooseList).blur();
    $(chooseList).next().val(chooseId);
    $('#firstCata').empty();
    $('#secondCata').empty();
    $('#thirdCata').empty();
    $("#showdiv").hide();
    $("#pop").hide();
});

$.ajax({
    type: "get",
    url: "http://purchasing.mhw001.com/getPurchasingDetailByShopId?purchase_id=777",
    dataType: "json",
    data: {
        // purchase_id: purId
    },
    success: function (result) {
        console.log(result.data);
        if (result.code == "1") {
            if (result.data != "") {
                FormUtil.set(result.data);
                //采购类型
                var purchType = result.data.purchase_type;
                if (purchType == "1") {
                    $("#processFlag").attr("checked", "true");
                } else {
                    $("#nowGoodFlag").attr("checked", "true");
                }
                //报价要求
                var conit = result.data.offer_demand;
                // console.log(conit);
                if (conit.length == 2) {
                    $("#haveTaxFlag").attr("checked", "true");
                    $("#invoice_tax").show();
                    $("#haveCarriFlag").attr("checked", "true");
                } else if (conit.length == 1) {
                    if (conit[0] == 0) {
                        $("#haveTaxFlag").attr("checked", "true");
                        $("#invoice_tax").show();
                    } else if (conit[0] == 1) {
                        $("#haveCarriFlag").attr("checked", "true");
                    }
                }
                // 发票类型
                var feeType = result.data.invoice_type;
                $("#invoice_type option").each(function () {
                    if (this.value == feeType) {
                        $(this).attr("selected", "selected");
                    }
                });
                //信息公开
                var openInfo = result.data.info_open;
                if (openInfo == "0") {
                    $("#loginPubFlag").attr("checked", "true");
                } else if (openInfo == "1") {
                    $("#pubFlag").attr("checked", "true");
                } else {
                    $("#noPubFlag").attr("checked", "true");
                }
                //资质要求
                var flavors = result.data.qualification_requirement;
                if (flavors != 0 && flavors != null && flavors != "" && flavors != undefined) {
                    $.each(flavors, function (i, item) {
                        $("input[name^='qualification_requirement'][value=" + item + "]").attr("checked", "checked");
                    });
                }
                // 交货地
                var deliveryPlace = result.data.deliveryId;
                var proPlace = deliveryPlace[0];
                $("#province option").each(function () {
                    if (this.value == proPlace) {
                        $(this).attr("selected", "selected");
                    }
                });
                $.ajax({
                    type: "get",
                    url: "http://purchasing.mhw001.com/getDistrictList",
                    dataType: "json",
                    data: {
                        'district_id': proPlace
                    },
                    success: function (res) {
                        var option2 = '';
                        for (var i = 0; i < res.data.length; i++) {
                            option2 += '<option value="' + res.data[i].district_id + '">' + res.data[i].district_name + '</option>';
                        }
                        $('#city').empty().append(option2);
                        $("#city option").each(function () {
                            if (this.value == deliveryPlace[1]) {
                                $(this).attr("selected", "selected");
                            }
                        });
                    }
                });
                //所在地区
                var areaPlace = result.data.areaId;
                if (areaPlace != 0 && areaPlace != null && areaPlace != "" && areaPlace != undefined) {
                    var areaPro = areaPlace[0];
                    $("#area_pro option").each(function () {
                        if (this.value == areaPro) {
                            $(this).attr("selected", "selected");
                        }
                    });
                    $.ajax({
                        type: "get",
                        url: "http://purchasing.mhw001.com/getDistrictList",
                        dataType: "json",
                        data: {
                            'district_id': areaPro
                        },
                        success: function (res) {
                            var option2 = '';
                            for (var i = 0; i < res.data.length; i++) {
                                option2 += '<option value="' + res.data[i].district_id + '">' + res.data[i].district_name + '</option>';
                            }
                            $('#area_city').empty().append(option2);
                            $("#area_city option").each(function () {
                                if (this.value == areaPlace[1]) {
                                    $(this).attr("selected", "selected");
                                }
                            });
                        }
                    })
                }
                //表格
                var tableCont = result.data.goods_info;
                rowCount = tableCont.length;
                var tableHtml = "";
                for (var i = 0; i < tableCont.length; i++) {
                    tableHtml += '<tr class="tabTr" id="enquiry_goods0">' +
                        '<td width="2%">' +
                        '<span class="removeBtn"><img src="/img/purchase/delete.png"></span>' +
                        '</td>' +
                        '<td width="10%" class="goods_name">' +
                        '<input class="bor_look" type="text" name="goods_name[0]" id="goods_name0" value="' + tableCont[i].goods_name + '">' +
                        '</td>' +
                        '<td width="23%" class="goods_type">' +
                        '<input class="bor_look choose_trade_type" type="text" name="cat_id_box[0]" id="cat_id_box0" placeholder="请选择商品分类" value="' + tableCont[i].cat_name + '">' +
                        '<input class="bor_look chooseClassify" type="hidden" name="cat_id[0]" id="cat_id0" value="' + tableCont[i].cat_id + '">' +
                        '</td>' +
                        '<td width="10%" class="brand">' +
                        '<input class="bor_look" type="text" name="goods_brand[0]" id="goods_brand0" value="' + tableCont[i].goods_brand + '">' +
                        '</td>' +
                        '<td width="10%" class="modal_num">' +
                        '<input class="bor_look" type="text" name="goods_type[0]" id="goods_type0" value="' + tableCont[i].goods_type + '">' +
                        '</td>' +
                        '<td width="15%" class="nature">' +
                        '<input class="bor_look" type="text" name="goods_property_detail[0]" id="goods_property_detail0" value="' + tableCont[i].goods_property_detail + '">' +
                        '</td>' +
                        '<td width="6%" class="buy_count">' +
                        '<input class="bor_look" type="text" name="purchase_number[0]" id="purchase_number0" value="' + tableCont[i].purchase_number + '">' +
                        '</td>' +
                        '<td width="6%" class="buy_unit">' +
                        '<input class="bor_look" type="text" name="unit[0]" id="unit0" value="' + tableCont[i].unit + '">' +
                        '</td>' +
                        '<td width="18%" class="good_pict">' +
                        '<div class="beforeUpload">' +
                        '<span class="upload_file">上传</span>' +
                        '<input class="bor_look uploadImg" type="file" accept="image/x-png,image/gif,image/jpeg,image/bmp" name="pict_list0" id="pict_list0">' +
                        '<input class="bor_look uploadUrl" type="hidden" id="goods_image0" name="goods_image[0]" value="' + tableCont[i].goods_image + '">' +
                        '</div>' +
                        '<div class="afterUpload" style="display:none">' +
                        '<span class="uploadTitle">' + tableCont[i].goods_basename + '</span>' +
                        '<span class="delBtn"><img src="/img/purchase/cha.png"></span>' +
                        '</div>' +
                        '</td>' +
                        '</tr>'
                }
                $("#addTr").empty().append(tableHtml);
                rowNum();
                reIndex();
                // 处理图片显示
                $(".uploadUrl").each(function () {
                    var nowVal = $(this).val();
                    if (nowVal == "") {
                        $(this).parent().show();
                        $(this).parent().parent().find(".beforeUpload").hide();
                    }else{
                        $(this).parent().hide();
                        $(this).parent().parent().find(".beforeUpload").show();
                    }
                })
                //处理附件
                var fuFile = result.data.basename;
                if (fuFile != "") {
                    $('.uploadAttach').hide();
                    $('.attachBox').show();
                    $(".attachTitle").text(fuFile);
                }
            } else {
                $("#addTr").html(addRowTemplate);
            }
        } else {
            alert(result.message);
        }
    }
});

var FormUtil = {
    //值回写方法 
    set: function (obj) {
        var attr;
        for (attr in obj) {
            try {
                var element = $("#" + attr)[0];
                var nodeName = element.nodeName;
                if (nodeName == "INPUT") {
                    FormUtil.judgeType($(element).attr("type"), attr, obj[attr]);
                } else if (nodeName == "TEXTAREA") {
                    FormUtil.setValue(attr, obj[attr]);
                }
            } catch (e) {
                continue;
            }
        }
    },
    //设置文本框 文本域 密码框 隐藏框  
    setValue: function (key, value) {
        $("#" + key).val(value);
    },
    //input类型判断  
    judgeType: function (type, key, value) {
        if (type == "text" || type == "password" || type == "hidden") {
            FormUtil.setValue(key, value);
        } else if (type == "radio") {
            FormUtil.setRadio(key, value);
        }
    }
};